package 中等;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class 找到字符串中所有字母异位词438 {

    public static void main(String[] args) {
        String s = "abab";
        String p = "ab";
        System.out.println(findAnagrams(s,p ));

    }

    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();
        Map<Character,Integer> need = new HashMap<>();
        Map<Character,Integer> window = new HashMap<>();
        char c;
        int length = s.length();
        for (int i = 0; i < p.length(); i++) {
            c = p.charAt(i);
            need.put(c, need.getOrDefault(c,0 )+1);
        }
        int left = 0;
        int right = 0;
        int valid = 0;
        while (right< length){
            c = s.charAt(right);
            right++;
            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0 )+1 );
                if (window.get(c).intValue()==need.get(c).intValue()){
                    valid++;
                }
            }
            while (right-left==p.length()){
                if (valid == need.size()){
                    list.add(left);
                }
                c = s.charAt(left);
                left ++;
                if (need.containsKey(c)){
                    window.put(c,window.get(c)-1 );
                    if (window.get(c).intValue()==need.get(c).intValue()-1){
                        valid--;
                    }
                }

            }
        }
        return list;
    }
}
